<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-button type="primary" @click="addExample">添加实例</el-button>
        <el-button type="primary" @click="operation('start')">启动</el-button>
        <el-select v-model="value" clearable placeholder="更多" style="width: 108px" @change="operation">
          <el-option v-for="(item,index) in options" :key="index" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>

      <el-col :span="12" class="ecs_col">
        <el-row>
          <el-col :span="9" style="margin:0 5px 0 -10px">
            <el-input maxlength="24" v-model="queryParam.ip" clearable placeholder="请输入管理IP"></el-input>
          </el-col>
          <el-col :span="7">
            <el-button type="primary" @click="queryEcsCluster(queryParam)">搜索</el-button>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="searchVisible =!searchVisible">高级搜索
              <i :class="[!searchVisible?adv_sty_hide : adv_sty_show]"/>
            </el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <nodeQuery :searchVisible="!searchVisible" :nodeType="nodeType" :installWay="installWay" :configSynState="configSynState" @nodeQuery="queryEcsCluster" :inputHolder="inputHolder"></nodeQuery>
    <el-row>
      <div v-loading="loading">
        <el-table @selection-change="handleSelectionChange" :data="data.records" le="width: 100%" :row-class-name="tableRowClassName">
          <el-table-column align="center" type="selection" prop="id" width="55"></el-table-column>
          <el-table-column align="center" prop="role" label="角色" sortable width="180">
            <template slot-scope="scope">
              <router-link style="text-decoration: none;color: #409EFF;" :to="jumpTo(scope.row.id)">{{scope.row.role}}
              </router-link>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="state" label="运行状态" sortable width="180">
            <template slot-scope="scope">
              <div v-if="scope.row.state == 'ACTIVE'">
                <div style="width: 8px;height: 8px;background-color: #1DC400 ;border-radius: 50%;display:inline-block"></div>
                <div style="display:inline-block">{{runStates[0].label}}</div>
              </div>
              <div v-else>
                <div style="width: 8px;height: 8px;background-color: red;border-radius: 50%;display:inline-block"></div>
                <div style="display:inline-block">{{runStates[2].label}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="configSynState" sortable label="配置状态">
            <template slot-scope="scope">
              <div v-if="scope.row.configSynState == 1">
                <img src="../../assets/img/xuanzhong.png">
                <div style="display:inline-block;">{{configSynState[0].label}}</div>
              </div>
              <div v-else>
                <img src="../../assets/img/xingzhuang.png">
                <div style="display:inline-block">{{configSynState[1].label}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="ecs.name" sortable label="主机名称"></el-table-column>

          <el-table-column align="center" prop="version" sortable label="版本">

            <template slot-scope="scope">
              <el-row v-if="scope.row.version==scope.row.newVersion">{{scope.row.version}}</el-row>
              <el-row v-if="scope.row.version!=scope.row.newVersion">{{scope.row.version}}
                <!--&ndash;&gt;{{scope.row.newVersion}}-->
                <span style="color: red;font-size: 10px;margin-left: 10px">{{updating?'正在升级':'可升级'}}</span>
              </el-row>
            </template>

          </el-table-column>

          <el-table-column align="center" prop="ecs.ip" sortable label="管理IP"></el-table-column>
          <el-table-column align="center" prop="ecs.serviceIp" sortable label="业务IP"></el-table-column>
        </el-table>
      </div>
    </el-row>

    <el-row>
      <el-col :span="12" :offset="12">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="data.current" :page-sizes="[10, 20, 30, 40]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="data.total"></el-pagination>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" v-model="dialogVisible" title="卸载实例" width="540px" @closed="closeDelDia">
      <el-checkbox v-model="removeDirectory" label="卸载实例是否同步删除目录？" size="large"></el-checkbox>
      <template #footer>
        <div class="adv_del">
          <el-button @click="dialogVisible = false;value = '';loading=false">取消</el-button>
          <el-button type="primary" @click="removeColonyOrNode">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="添加实例" :close-on-click-modal="false" :visible.sync="example" top="292px" width="820px">
      <el-form :model="addExampleObj" status-icon :rules="rules" ref="addExampleObj" label-width="100px">
        <el-row>
          <el-col :span="24" style="margin-left: 50px;">
            <div style="width: 90%">
              <el-table :data="allUnboundHosts" :header-cell-style="{'background-color':'#F5F5F5','color':'#333333 ','font-size':'12px','text-align':'center','padding':'0','height':'12px','line-height':'12px'}">
                <el-table-column align="center" prop="name" label="主机名称" width="140"></el-table-column>
                <el-table-column align="center" prop="ip" label="管理IP" width="140"></el-table-column>
                <el-table-column align="center" prop="serviceIp" label="业务IP" width="140"></el-table-column>

                <el-table-column align="center" prop="nodeType" label="角色" width="250">
                  <el-table-column>
                    <template slot="header">
                      <div>
                        <el-checkbox v-model="selectAllWorkFlag" @change="selectAllWork"></el-checkbox>
                        worker({{workNodeNum}})
                      </div>
                    </template>
                    <template slot-scope="scope" class="node_div">
                      <el-checkbox style="margin-right:0;padding-left:40px" v-model="scope.row.workerNodes" @change="aloneSleWork"></el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      <div>
                        <el-checkbox v-model="selectAllcoordinatorFlag" @change="selectAllcoordinator"></el-checkbox>
                        coordinator({{coordinatorNodeNum}})
                      </div>
                    </template>
                    <template slot-scope="scope" class="node_div">
                      <el-checkbox style="margin-right:0;padding-left:40px" v-model="scope.row.coordinator" @change="aloneSleCoordinator"></el-checkbox>
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px;margin-left: 40px;">
          <el-col :span="5">
            <el-form-item label="安装方式:" prop="upgradeWay">
              <el-select clearable class="add_clu_input" style="width:90px;" v-model="addExampleObj.upgradeWay" placeholder="请选择安装方式">
                <el-option v-for="item in upgradeWays" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14" style="margin-left: 40px;display:flex;line-height:40px">
            <el-form-item :label="addExampleObj.upgradeWay==2?'安 装 包 :':'版 本 号 :'" prop="fieldId">
              <el-select clearable class="add_clu_input" @focus="queryPackageList(addExampleObj.upgradeWay)" :loading="selectLoading" v-model="addExampleObj.fileId" :placeholder="addExampleObj.upgradeWay==2?'请选择安装包':'请选择版本号'">
                <el-option v-for="item in packageFileList" :key="item.id" :label="item.version" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <i @click="showUploadPackage" class="iconfont icon-shangchuan shangchuanSty" v-if="addExampleObj.upgradeWay ==2"></i>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14" style="margin-left: 40px;">
            <el-form-item label="安 装 路 径 :" prop="installationPath">
              <el-input clearable class="add_clu_input" v-model="addExampleObj.installationPath" placeholder="请输入安装路径"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20" style="margin-left: 160px;">
            <el-form-item>
              <el-button @click="example=false">取 消</el-button>
              <el-button type="primary" style="margin-left: 50px;" @click="addNode(addExampleObj)">确 定</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <el-dialog :visible.sync="updateStated" width="720px" v-loading="updateloading">
      <div>
        <span class="updateFont">升级方式</span>
        <el-select class="add_clu_input" style="width:90px;" v-model="updategradeWay" placeholder="请选择升级方式">
          <el-option v-for="item in updategradeWays" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </div>
      <div class="installPackage" style="display:flex;line-height:40px">
        <span class="updateFont2">{{updategradeWay==2?"安装包":"版本号"}}</span>
        <el-select class="add_clu_input" @focus="updatePackageList(updategradeWay)" v-model="updatefileId" :placeholder="updategradeWay==2?'请选择安装包':'请选择版本号'">
          <el-option v-for="item in updatepackageFileList" :key="item.id" :label="item.version" :value="item.id"></el-option>
        </el-select>
         <i @click="showUploadPackage" class="iconfont icon-shangchuan shangchuanSty" v-if="updategradeWay ==2"></i>
      </div>
      <div class="installBtns">
        <el-button @click="updateStated=false;updateloading=false">取 消</el-button>
        <el-button type="primary" style="margin-left: 50px;" @click="updateState">确 定</el-button>
      </div>
    </el-dialog>
    <uploadPackage v-if="uploadVis" @closeAfter="closeAfter"></uploadPackage>
  </div>
</template>
<script>
  import uploadPackage from '@/components/upload/uploadPackage'
  import {doGet, doPost} from '@/api/index.js'
  import nodeQuery from '../../components/nodeQuery/nodeQuery.vue'
  import pubsub from 'pubsub-js'
  export default {
      props: {},
      name: 'node-list',
      components: {
          nodeQuery,uploadPackage
      },
      created() {
          this.clusterCode = this.$route.query.clusterCode
      },
      mounted() {
          this.queryEcsCluster({});
          pubsub.subscribe("shuaxin",data=>{
            this.queryEcsCluster({});
          })
          this.token = JSON.parse(localStorage.getItem('userInfo')).authorization;
          this.timer = setInterval(() => {
            if(this.flag){
              this.queryEcsClusterInterval({});
            }
          }, 1000);
      },
      beforeDestroy() {
          clearInterval(this.timer);
      },
      watch: {
          selectAllWorkFlag() {
              this.workNodeNum = this.allUnboundHosts.filter(item => item.workerNodes).length
          },
          selectAllcoordinatorFlag() {
              this.coordinatorNodeNum = this.allUnboundHosts.filter(item => item.coordinator).length
          }
      },
      methods: {
        closeAfter(flag){
          this.uploadVis=flag;
        },
          closeDelDia() {
              this.value = '';
          },
          handleSelectionChange(val) {
              this.nodeIds = [];
              val.forEach(i => {
                  this.nodeIds.push(i.id)
              })
          },
          operation(val) {
              if (this.nodeIds.length == 0) {
                  this.value = '';
                  return this.$message.error("请至少选择一个实例进行操作");
              }
              if (val != "") {
                  this.loading = true;
              }
              //start, shut down, delete, upgrade node
              if (val == 'stop' || val == 'restart' || val=='start') {
                if(val=='start')
                {
                  val='restart'
                }
                  this.changeClassState(val);
              } else if (val == 'del') {
                  this.dialogVisible = true;
              } else if (val == 'upgrade') {
                  this.loading = false;
                  this.updateStated = true;
                  this.value = '';
              }
          },
          //get the version of upgrade
          updatePackageList(way) {
              if (way) {
                  let url = '/sys_file/listFileNoPage?upgradeWay=' + way
                  doGet(url).then(res => {
                      if (res.data.code == 0) {
                          this.updatepackageFileList = res.data.data
                      }
                  })
              }
          },
          //upgrade version
          updateState() {
              if (this.updategradeWay == "") return this.$message('请选择安装方式')
              if (this.updatefileId == "")
              {
                if(updategradeWay==2)
                {
                  return this.$message('请选择安装包')
                }
                else
                {
                  return this.$message('请选择版本号')
                }
              }
              let dataObj = {
                  fileId: this.updatefileId,
                  isStart: true,
                  nodeIds: this.nodeIds
              }
              this.updateloading = true;
              let url = "/sys_openlookeng_cluster/updateClusterVersion";
              doPost(url, dataObj).then(res => {
                  this.updateloading = false;
                  if (res.data.code == 0) {
                      this.updateStated = false;
                      this.loading = false;
                      this.updating = false;
                      this.queryEcsCluster({});
                      this.$message({
                          message: '操作成功',
                          type: 'success'
                      });
                  }
              })
          },
          //uninstall node
          removeColonyOrNode() {
              this.dialogVisible = false;
              let obj = {
                  'removeDirectory': this.removeDirectory,
                  'state': 'stop',
                  'nodeIds': this.nodeIds
              };
              let url = '/sys_openlookeng_cluster/removeColonyOrNode';
              doPost(url, obj).then(res => {
                  // this.value='';
                  // this.nodeIds=[];
                  if (res.data.code == 0) {
                      this.$message.success(res.data.msg);
                      this.loading = false;
                      this.queryEcsCluster({});
                  } else {
                      this.loading = false;
                  }
              });
          },
          //start,shut down,restart node
          changeClassState(state) {
              let obj = {
                  'state': state,
                  'nodeIds': this.nodeIds
              };
              let url = '/sys_openlookeng_cluster/changeClassState';
              doPost(url, obj).then(res => {
                  this.value='';
                  this.nodeIds=[];
                  if (res.data.code == 0) {
                      this.$message.success(res.data.msg);
                      this.loading = false;
                      this.queryEcsCluster({});
                  } else {
                      this.loading = false;
                  }
              });
          },
          aloneSleCoordinator(val) {
              this.coordinatorNodeNum = this.allUnboundHosts.filter(item => item.coordinator).length
              this.selectAllcoordinatorFlag = false;
              if (this.coordinatorNodeNum == this.allUnboundHosts.length) {
                  this.selectAllcoordinatorFlag = true;
              }
          },
          selectAllcoordinator(val) {
              this.allUnboundHosts.forEach(item => {
                  item.coordinator = val;
              });
          },
          aloneSleWork(val) {
              this.workNodeNum = this.allUnboundHosts.filter(item => item.workerNodes == true).length
              this.selectAllWorkFlag = false;
              if (this.workNodeNum == this.allUnboundHosts.length) {
                  this.selectAllWorkFlag = true;
              }
          },
          selectAllWork(val) {
              this.allUnboundHosts.forEach(item => {
                  item.workerNodes = val;
              });
          },
          checkBoxChange(id, nodeType) {
              let dto = {
                  'ecsId': id,
                  'nodeType': nodeType
              }
              this.addExampleObj.dtos.push(dto);
          },
          //add node
          addNode(obj) {
              let _this = this;
              this.addExampleObj.dtos = [];
              this.allUnboundHosts.forEach(i =>
              {
                  if (i.workerNodes == true && i.coordinator == true)
                  {
                      let dto = {
                          'ecsId': i.id,
                          'nodeType': "ALL"
                      }
                      this.addExampleObj.dtos.push(dto);
                  }
                  else if (i.workerNodes == true)
                  {
                      let dto = {
                          'ecsId': i.id,
                          'nodeType': "WORKER_NODES"
                      }
                      this.addExampleObj.dtos.push(dto);
                  }
                  else if (i.coordinator == true)
                  {
                      let dto = {
                          'ecsId': i.id,
                          'nodeType': "COORDINATOR"
                      }
                      this.addExampleObj.dtos.push(dto);
                  }
              })
              if (obj.dtos.length == 0)
              {
                  this.$message.error("请至少选择一个主机");
              }
              else
              {
                  this.loading = true;
                  let url = "/sys_openlookeng_cluster/addNode";
                  doPost(url, obj).then(res => {
                      _this.loading = false;
                      if (res.data.code == 0) {
                          _this.$message.success(res.data.msg);
                          _this.loading = false;
                      }
                      _this.queryEcsCluster({});
                  })
              }
              this.example = false;
          },
          queryPackageList(way) {
              // debugger
              if (way) {
                  this.selectLoading = true;
                  let url = "/sys_file/listFileNoPage?upgradeWay=" + way;
                  doGet(url).then(res => {
                      this.selectLoading = false;
                      if (res.data.code == 0) {
                          this.packageFileList = res.data.data;
                      }
                  });
              }
          },
          diaBeforeClose() {
              this.version = '';
          },
          showUploadPackage() {
              // this.uploadPackageFileList = [];
              this.uploadVis = true;
          },
          clearaddClusterObjField() {
              this.addExampleObj.fieldId = '';
          },
          getAllUnboundHosts() {
              let url = "/sys_ecs/getAllUnboundHosts";
              doGet(url, null).then(res => {
                  if (res.data.code === 0) {
                      this.allUnboundHosts = res.data.data;
                  }
              });
          },
          addExample() {
            this.allUnboundHosts = [];
            this.coordinatorNodeNum = 0;
            this.workNodeNum = 0;
            let i = this.workNodeNum
            let e = this.coordinatorNodeNum
            // debugger
            this.selectAllWorkFlag = false;
            this.selectAllcoordinatorFlag = false;
            this.addExampleObj = {
              'type': 1,
              'upgradeWay': '',
              'fileId': '',
              'version': '',
              'dtos': [],
              'isStart': true
            }
            this.getAllUnboundHosts();
            this.example = true;
          },
          jumpTo(id) {
              return {path: '/node-detail', query: {clusterId: id}};
          },
          queryEcsCluster(obj) {
              // this.loading=true;
              let url = "/sys_openlookeng_cluster/page";
              obj.type = 2;
              obj.ip = this.queryParam.ip;
              obj.pageNo = this.data.pageNo;
              obj.pageSize = this.data.pageSize;
              doPost(url, obj).then(res => {
                  // this.loading=false;
                  if (res.data.code === 0) {
                      this.data.records = res.data.data.records;
                      this.data.total = res.data.data.total;
                  }
              });
          },
          queryEcsClusterInterval(obj) {
              if (!this.data.records) return
              let that=this;
              let url = "/sys_openlookeng_cluster/page";
              obj.type = 2;
              obj.ip = "";
              obj.pageNo = this.data.pageNo;
              obj.pageSize = this.data.pageSize;
              this.flag = false;
              doPost(url, obj).then(res =>
              {
                if (res.data.code === 0) {
                  let response = res.data.data.records;
                  for (let j=0;j<response.length;j++)
                  {
                    for (let i = 0; i < that.data.records.length; i++)
                    {
                      if (that.data.records[i].id == response[j].id)
                      {
                        that.data.records[i].state = response[j].state;
                        that.data.records[i].version = response[j].version;
                      }
                    }
                  }
                  that.data.total = res.data.data.total;
                }
                setTimeout(()=>{
                  that.flag = true;
                },2000)
              });
          },
          handleSizeChange(val) {
              this.data.pageSize = val;
              this.queryEcsCluster({})
          },
          handleCurrentChange(val) {
              this.data.pageNo = val;
              this.queryEcsCluster({})
          },
          tableRowClassName({row, rowIndex}) {
              if (rowIndex === 1) {
                  return 'warning-row'
              } else if (rowIndex === 3) {
                  return 'success-row'
              }
              return ''
          }
      },
      data() {
          return {
              timer: '',
              flag:true,
              updateloading: false,
              updating: false,
              upgradeWays: [{label: '在线', value: '1'}, {label: '离线', value: '2'}],
              updatepackageFileList: [],
              updategradeWay: '',
              updatefileId: '',
              updateStated: false,
              dialogVisible: false,
              removeDirectory: false,
              nodeIds: [],
              loading: false,
              selectAllcoordinatorFlag: false,
              workNodeNum: 0,
              coordinatorNodeNum: 0,
              selectAllWorkFlag: false,
              selectLoading: false,
              token: '',
              version: '',
              packageFileList: [],
              uploadLoadVis: false,
              uploadVis: false,
              updategradeWays: [{label: '在线', value: '1'}, {label: '离线', value: '2'}],
              allUnboundHosts: [],
              rules: {
                  ecsId: [{required: true, message: '请选择主机', trigger: 'change'}],
                  nodeType: [{required: true, message: '请选择角色', trigger: 'change'}],
                  upgradeWay: [{required: true, message: '请选择升级方式', trigger: 'blur'}],
                  sysFileId: [{required: true, message: '请选择', trigger: 'blur'}],
                  fieldId: [{required: true, message: '请选择', trigger: 'blur'}],
                  installationPath: [{required: true, message: '请填写', trigger: 'blur'}],
              },
              addExampleObj: {
                  'type': 1,
                  'upgradeWay': '',
                  'fileId': '',
                  'version': '',
                  'dtos': [],
                  'installationPath':'/opt/openlookeng/'
              },
              upgrade: '',
              example: false,
              runStates: [{
                  value: 'ACTIVE',
                  label: '运行中'
              }, {
                  value: 'INACTIVE',
                  label: '空闲'
              }, {
                  value: 'SHUTTING_DOWN',
                  label: '停止'
              }],
              configSynState: [{
                  value: '1',
                  label: '已同步'
              }, {
                  value: '2',
                  label: '未同步'
              }],
              installWay: [{
                  value: '1',
                  label: '在线'
              }, {
                  value: '2',
                  label: '离线'
              }],
              nodeType: [{
                  value: 'ALL',
                  label: '两者'
              }, {
                  value: 'COORDINATOR',
                  label: '协调节点'
              }, {
                  value: 'WORKER_NODES',
                  label: '工作节点'
              }],
              adv_sty_hide: "iconfont icon-xiangshangzhanhang",
              adv_sty_show: "iconfont icon-xiangxiazhanhang",
              inputHolder: ["请选择实例类型", "请选择升级方式", "请选择同步状态"],
              searchVisible: true,
              queryParam: {
                  'ip': '',
                  'configSynState': '',
                  'installWay': '',
                  'nodeType': ''
              },
              clusterCode: '',
              options:
              [
                {
                    value: 'stop',
                    label: '停止'
                },
                {
                  value: 'restart',
                  label: '重启'
                },
                {
                    value: 'del',
                    label: '卸载'
                },
                {
                    value: 'upgrade',
                    label: '升级'
                }
              ],
              value: '',
              data: {
                  pageNo: '1',
                  pageSize: '10',
                  total: 1,
                  current: 1,
                  records: []
              }
          }
      }
  }
</script>


<style scoped>
.shangchuanSty {
    color: #409EFF;
    font-size: 28px !important;
    cursor: pointer;
    padding-left: 10px;
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .installPackage, .installBtns {
    margin-top: 20px;
  }

  .updateFont {
    /* letter-spacing: 1.5px; */
    width:50px;
  }

  .updateFont2 {
    /* letter-spacing: 7.5px; */
    width:60px;
  }

  .installBtns {
    margin-left: 63%;
  }
</style>
